package com.atguigu.gmall.user.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.common.constant.RedisConst;
import com.atguigu.gmall.user.model.UserInfo;
import com.atguigu.gmall.user.mapper.UserInfoMapper;
import com.atguigu.gmall.user.service.UserInfoService;
import com.atguigu.gmall.user.util.AreaInfo;
import com.atguigu.gmall.user.util.BaiDuService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * 用户表 业务实现类
 *
 * @author atguigu
 * @since 2023-05-04
 */
@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements UserInfoService {

    @Autowired
    private RedisTemplate redisTemplate;


    /**
     * 用户登录管理
     *
     * @param userInfo
     * @param httpServletRequest
     * @return
     */
    @Override
    public Map login(UserInfo userInfo, HttpServletRequest httpServletRequest) {
        //根据账号(用户名、手机号等)查询用户记录
        LambdaQueryWrapper<UserInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserInfo::getLoginName,userInfo.getLoginName());
        queryWrapper.or().eq(UserInfo::getEmail,userInfo.getLoginName());
        queryWrapper.or().eq(UserInfo::getPhoneNum,userInfo.getLoginName());
        //将提交的密码进行加密
        UserInfo loginUser = this.getOne(queryWrapper);
        String password = DigestUtils.md5DigestAsHex(userInfo.getPasswd().getBytes());
        //判断密码是否一致
        if (loginUser.getPasswd().equals(password)){
        //如果验证通过
            //生成一个令牌UUID
            String token = UUID.randomUUID().toString().replaceAll("-", "").toString();
            String userKey = RedisConst.USER_KEY_PREFIX+token;
            //将用户信息存入Redis,key:uuid,val:用户信息
            JSONObject userInfoJsonObject = new JSONObject();

            userInfoJsonObject.put("id",loginUser.getId());
//            String ipAddress = IpUtil.getIpAddress(httpServletRequest);
            String ipAddress = "111.194.161.162";
            AreaInfo area = BaiDuService.getArea(ipAddress);
            if (area!=null){
                //todo 存储设备唯一标识，需要手机端获取手机硬件信息提交服务端
                userInfoJsonObject.put("ipCity",area.getCity());
            }

            redisTemplate.opsForValue().set(userKey,userInfoJsonObject,30, TimeUnit.MINUTES);
            //将生成令牌跟用户信息响应给客户端浏览器
            HashMap<String, Object> resultMap = new HashMap<>();
            resultMap.put("token",token);
            resultMap.put("nickName",loginUser.getNickName());
            return resultMap;
        }else {
            throw new RuntimeException("用户名或密码错误，请重试！");
        }
    }

    /**
     * 用户退出登录管理
     * @param token 用户令牌
     * @return
     */
    @Override
    public void logout(String token) {
        //将当前用户登录时存入redis的令牌删除
            //创建用户登录时存入token的key
        String tokenKey = RedisConst.USER_KEY_PREFIX+token;
            //删除key
        redisTemplate.delete(tokenKey);
    }
}
